package webapi

import (
	"MqttCloudProtocolServer/publiclib/datamodel/dborm"
	"MqttCloudProtocolServer/publiclib/dbcontrol"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/wonderivan/logger"
)

//GatewayServerManagerService 网关服务器注册API类。注册控制台
type GatewayServerManagerService struct {
	base ServiceBase
}
type importResModel struct {
	//Tcp null
	TCP *dborm.Manageserver
	//Gateway null
	Gateway *dborm.Mqttconf
	//User null
	User string
}

//Regist 注册
func (_this *GatewayServerManagerService) Regist(mux *http.ServeMux) {
	_this.base.Regist(mux)
	_this.base.path += "gsm"
	_this.base.HandleRegist("getGateways", _this.getGateways)
	_this.base.HandleRegist("addGateways", _this.addGateway)
	_this.base.HandleRegist("saveConfig", _this.saveConfig)
	_this.base.HandleRegist("getGatewayTCP", _this.getGatewayTCP)
	_this.base.HandleRegist("getProtocols", _this.getProtocols)
	_this.base.HandleRegist("removeItem", _this.removeItem)
	_this.base.HandleRegist("importSettings", _this.importOldSettings)
}

//importOldSettings 导入旧的配置文件
func (_this *GatewayServerManagerService) importOldSettings(w http.ResponseWriter, r *http.Request) {
	result, err := ioutil.ReadAll(r.Body)
	if err != nil {
		logger.Alert(err)
		fmt.Fprintln(w, "参数错误 error")
		return
	}
	datas := new(importResModel)
	err2 := json.Unmarshal(result, datas)
	logger.Debug(datas.TCP.HostPort)
	logger.Debug(datas.Gateway.ClientName)
	if err2 != nil {
		logger.Alert(err2)
		return
	}
	{
		control := dbcontrol.CreateTcpconfControl()
		control.CreateNew()
		datas.TCP.UUID = control.Data.UUID
		datas.TCP.HostIP = "0.0.0.0"
		control.Data = datas.TCP
		if !_this.saveTCP(control, w, result) {
			fmt.Fprintln(w, "Failed")
			logger.Alert("保存错误")
			return
		}
	}

	{
		control := dbcontrol.CreateMqttconfControl()
		control.CreateNew()
		datas.Gateway.MasterID = datas.TCP.UUID
		datas.Gateway.UUID = control.Data.UUID
		control.Data = datas.Gateway
		if !_this.saveMqtt(control, w, result) {
			fmt.Fprintln(w, "Failed")
			logger.Alert("保存错误")
			return
		}
	}

	{
		user := datas.User
		controlUser := dbcontrol.CreateUserconfControl()
		if err := controlUser.FindByName(user); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		control := _this.userServerControl(w, result)
		control.Data.UserID = controlUser.Data.UUID
		control.Data.MqttConfID = datas.Gateway.UUID
		if !_this.saveUserServer(control, w, result) {
			fmt.Fprintln(w, "Failed")
			logger.Alert("保存错误")
			return
		}
	}
}

//AddGateway 增加一个网关连接请求
func (_this *GatewayServerManagerService) addGateway(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		id := GetParam(vars, "id")
		pubTopic1 := GetParam(vars, "pub1")
		subTopic1 := GetParam(vars, "sub1")
		pubTopic2 := GetParam(vars, "pub2")
		subTopic2 := GetParam(vars, "sub2")
		user := GetParam(vars, "user")
		controlUser := dbcontrol.CreateUserconfControl()
		if err := controlUser.FindByName(user); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		logger.Info("id=" + id + "	pub1:" + pubTopic1 + "	sub1:" + subTopic1 + "	pub2:" + pubTopic2 + "	sub2:" + subTopic2 + " user:" + user)

		controlTCP := dbcontrol.CreateTcpconfControl()
		controlTCP.CreateNew()
		controlTCP.Data.HostIP = "0.0.0.0"
		controlTCP.Data.Mode = 2
		controlTCP.Data.MqttServerID = 1
		controlTCP.Data.Protocol = 1
		if err := controlTCP.Save(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		controlMqtt := dbcontrol.CreateMqttconfControl()
		controlMqtt.CreateNew()
		controlMqtt.Data.ClientName = id
		controlMqtt.Data.MasterID = controlTCP.Data.UUID
		controlMqtt.Data.PubTopic = pubTopic1
		controlMqtt.Data.SubTopic = subTopic1
		controlMqtt.Data.Retained = 0
		if err := controlMqtt.Save(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		controlUserServer := dbcontrol.CreateUserserverControl()
		controlUserServer.CreateNew()
		controlUserServer.Data.UserID = controlUser.Data.UUID
		controlUserServer.Data.MqttConfID = controlMqtt.Data.UUID
		if err := controlUserServer.Save(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		fmt.Fprintln(w, "Success")

	} else {
		fmt.Fprintln(w, "参数错误 error")

	}
}

func (_this *GatewayServerManagerService) getMqttControl(w http.ResponseWriter, result []byte) *dbcontrol.MqttconfControl {
	control := dbcontrol.CreateMqttconfControl()
	control.CreateNew()
	err2 := json.Unmarshal(result, control.Data)
	if err2 != nil {
		logger.Alert(err2)
		return nil
	}
	return control
}
func (_this *GatewayServerManagerService) saveMqtt(control *dbcontrol.MqttconfControl, w http.ResponseWriter, result []byte) bool {
	if control == nil {
		return false
	}
	err2 := control.Save()
	if err2 != nil {
		logger.Alert(err2)
		fmt.Fprintln(w, "参数错误 error")
		return false
	}
	return true
}
func (_this *GatewayServerManagerService) getTCPControl(w http.ResponseWriter, result []byte) *dbcontrol.ManageServerControl {
	control := dbcontrol.CreateTcpconfControl()
	control.CreateNew()
	err2 := json.Unmarshal(result, control.Data)
	if err2 != nil {
		logger.Alert(err2)
		return nil
	}
	return control
}
func (_this *GatewayServerManagerService) saveTCP(control *dbcontrol.ManageServerControl, w http.ResponseWriter, result []byte) bool {
	if control == nil {
		return false
	}
	err2 := control.Save()
	if err2 != nil {
		logger.Alert(err2)
		fmt.Fprintln(w, "参数错误 error")
		return false
	}
	return true
}
func (_this *GatewayServerManagerService) userServerControl(w http.ResponseWriter, result []byte) *dbcontrol.UserserverControl {
	control := dbcontrol.CreateUserserverControl()
	control.CreateNew()
	err2 := json.Unmarshal(result, control.Data)
	if err2 != nil {
		logger.Alert(err2)
		return nil
	}
	return control
}
func (_this *GatewayServerManagerService) saveUserServer(control *dbcontrol.UserserverControl, w http.ResponseWriter, result []byte) bool {
	if control == nil {
		return false
	}
	err2 := control.Save()
	if err2 != nil {
		logger.Alert(err2)
		fmt.Fprintln(w, "参数错误 error")
		return false
	}
	return true
}

//SaveConfig 保存配置文件
func (_this *GatewayServerManagerService) saveConfig(w http.ResponseWriter, r *http.Request) {
	result, err := ioutil.ReadAll(r.Body)
	if err != nil {
		logger.Alert(err)
		fmt.Fprintln(w, "参数错误 error")
		return
	}
	vars := r.URL.Query()
	if len(vars) > 0 {
		target := GetParam(vars, "target")
		switch target {
		case "mqtt":
			control := _this.getMqttControl(w, result)
			if _this.saveMqtt(control, w, result) {
				fmt.Fprintln(w, "Success")
			} else {
				fmt.Fprintln(w, "Failed")
				logger.Alert("保存错误")
			}
			//break
		case "tcp":
			control := _this.getTCPControl(w, result)
			if _this.saveTCP(control, w, result) {
				fmt.Fprintln(w, "Success")
			} else {
				fmt.Fprintln(w, "Failed")
				logger.Alert("保存错误")
			}
			//break
		case "new_mqtt":
			masterid := GetParam(vars, "masterid")
			if masterid != "" && masterid != "undefined" {
				control := _this.getMqttControl(w, result)
				control.Data.MasterID = masterid
				control.Data.PubTopic = "hd-" + control.Data.ClientName + "-1-p"
				control.Data.SubTopic = "hd-" + control.Data.ClientName + "-1-s"
				if _this.saveMqtt(control, w, result) {
					bytes, err2 := json.Marshal(control.Data)
					if err2 != nil {
						fmt.Fprintln(w, "Failed")
						logger.Alert("返回对象序列化错误")
						break
					}
					fmt.Fprintln(w, string(bytes[:]))
				} else {
					fmt.Fprintln(w, "Failed")
					logger.Alert("保存错误")
				}
			} else {
				fmt.Fprintln(w, "Failed")
				logger.Alert("没有传入关联主键")
			}
			//break
		case "new_tcp":
			control := _this.getTCPControl(w, result)
			control.Data.HostIP = "0.0.0.0"
			control.Data.Mode = 2
			control.Data.MqttServerID = 1
			if _this.saveTCP(control, w, result) {
				bytes, err2 := json.Marshal(control.Data)
				if err2 != nil {
					fmt.Fprintln(w, "Failed")
					logger.Alert("返回对象序列化错误")
					break
				}
				fmt.Fprintln(w, string(bytes[:]))
			} else {
				fmt.Fprintln(w, "Failed")
				logger.Alert("保存错误")
			}
			//break
		case "usermqtt":
			user := GetParam(vars, "user")
			uuid := GetParam(vars, "uuid")
			if user != "" && uuid != "" && user != "undefined" && uuid != "undefined" {

				controlUser := dbcontrol.CreateUserconfControl()
				if err := controlUser.FindByName(user); err != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				control := _this.userServerControl(w, result)
				control.Data.UserID = controlUser.Data.UUID
				control.Data.MqttConfID = uuid
				if _this.saveUserServer(control, w, result) {
					fmt.Fprintln(w, "Success")
					break
				} else {
					fmt.Fprintln(w, "Failed")
					logger.Alert("保存错误")
				}
				break
			}
		}
	}
}

//GetGateways 获取网关列表
func (_this *GatewayServerManagerService) getGateways(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) <= 0 {
		return
	}
	userName := GetParam(vars, "user")
	if userName == "" || userName == "undefined" {
		return
	}
	user := dbcontrol.CreateUserconfControl()
	if err := user.FindByName(userName); err != nil || user.Data == nil {
		logger.Alert(err)
	}
	if err := user.GetChildrenUserServers(); err != nil {
		logger.Alert(err)
	}
	if user.ChildrenUserServers == nil {
		logger.Alert("没有找到用户")
	}
	mqtts := make([]*dborm.Mqttconf, len(user.ChildrenUserServers))
	for index, item := range user.ChildrenUserServers {
		if err := item.GetParentMqttConf(); err != nil {
			logger.Alert(err)
		}
		mqtts[len(user.ChildrenUserServers)-index-1] = item.ParentMqttConf.Data
	}
	if bytes, err := json.Marshal(mqtts); err != nil {
		logger.Alert("没有找到用户")
	} else {
		fmt.Fprintln(w, string(bytes[:]))
	}
}

//getGatewayTCP 获取网关的TCP配置
func (_this *GatewayServerManagerService) getGatewayTCP(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		tcpID := GetParam(vars, "key")
		tcpControl := dbcontrol.CreateTcpconfControl()
		if err := tcpControl.FindByID(tcpID); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "查询错误Error")
			return
		}
		bytes, err := json.Marshal(tcpControl.Data)
		if err != nil {
			logger.Alert(err)
			return
		}
		fmt.Fprintln(w, string(bytes[:]))
	} else {
		fmt.Fprintln(w, "参数错误 error")

	}
}

//getProtocols fun
func (_this *GatewayServerManagerService) getProtocols(w http.ResponseWriter, r *http.Request) {
	protocolControl := dbcontrol.CreateProtocolenumControl()
	protocols, err := protocolControl.GetAll()
	if err != nil {
		logger.Alert(err)
		return
	}
	bytes, err2 := json.Marshal(protocols)
	if err2 != nil {
		logger.Alert(err2)
		return
	}
	fmt.Fprintln(w, string(bytes[:]))
}

//removeItem 获取网关的TCP配置
func (_this *GatewayServerManagerService) removeItem(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		mqttID := GetParam(vars, "key")
		control := dbcontrol.CreateMqttconfControl()
		if err := control.FindByID(mqttID); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		if err := control.GetParentTCPConf(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		if err := control.ParentTCPConf.GetChildrenMqttconf(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		if err := control.GetChildrenUserServer(); err != nil {
			logger.Alert(err)
			fmt.Fprintln(w, "Failed")
			return
		}
		for _, item := range control.ChildrenUserServer {
			if err := item.Delete(); err != nil {
				logger.Alert(err)
				fmt.Fprintln(w, "Failed")
				return
			}
		}
		if len(control.ParentTCPConf.ChildrenMqttconf) > 1 {
			if err := control.Delete(); err != nil {
				logger.Alert(err)
				fmt.Fprintln(w, "Failed")
				return
			}
			fmt.Fprintln(w, "Success")
		} else {
			if err := control.Delete(); err != nil {
				logger.Alert(err)
				fmt.Fprintln(w, "Failed")
				return
			}
			fmt.Fprintln(w, "Success")
			if err := control.ParentTCPConf.Delete(); err != nil {
				logger.Alert(err)
				return
			}
		}
	}
}
